import base64
import pickle
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """合并购物车工具函数"""
    # 1.读取cookie中购物车数据
    cart_cookie = request.COOKIES.get('cart')
    if cart_cookie is None:
        return response
    # cart_cookie_dict = {
    #     sku_id:{
    #         'count': count,
    #         'selected': selected
    #     }
    # }
    cart_cookie_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))

    # 2.读取redis中购物车数据
    redis_conn = get_redis_connection('cart')
    # sku_id: count  cart_redis = {b'1': b'10', b'2': b'15'}
    cart_redis = redis_conn.hgetall('cart_%s' % user.id)
    # selected_redis = {1, 2, 3, 4}
    selected_redis = redis_conn.smembers('selected_%s' % user.id)

    new_cart_redis = {}
    for sku_id, count in cart_redis.items():
        new_cart_redis[int(sku_id)] = int(count)

    # 3.将cookie中的购物车数据,合并到redis中
    for sku_id, cookie_dict in cart_cookie_dict.items():
        new_cart_redis[sku_id] = cookie_dict['count']

        if cookie_dict['selected']:
            selected_redis.add(sku_id)
    # 使用redis管道进行优化
    pl = redis_conn.pipeline()
    pl.hmset('cart_%s' % user.id, new_cart_redis)
    pl.sadd('selected_%s' % user.id, *selected_redis)
    # 执行管道
    pl.execute()

    # 4.清空cookie中的购物车数据
    response.delete_cookie('cart')

    # 返回响应信息
    return response
